package com.example.icongyou.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.icongyou.R;
import com.example.icongyou.bean.TaskDashboardBean;
import java.util.ArrayList;
import java.util.List;

/**
 * 任务列表适配器：展示任务基本信息、提交率、查看/讨论次数
 */
public class TaskItemAdapter extends RecyclerView.Adapter<TaskItemAdapter.TaskViewHolder> {
    private Context context;
    private List<TaskDashboardBean.TaskItemBean> taskList = new ArrayList<>();

    // 构造方法
    public TaskItemAdapter(Context context) {
        this.context = context;
    }

    // 设置任务数据（外部调用更新）
    public void setTaskList(List<TaskDashboardBean.TaskItemBean> taskList) {
        this.taskList = taskList != null ? taskList : new ArrayList<>();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 加载任务项布局
        View itemView = LayoutInflater.from(context)
                .inflate(R.layout.item_task, parent, false);
        return new TaskViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
        TaskDashboardBean.TaskItemBean task = taskList.get(position);

        // 绑定数据到控件
        holder.tvTaskName.setText("任务名称：" + task.getTaskName());
        holder.tvDeadline.setText("截止时间：" + task.getDeadline());
        // 核心要求过长时自动换行（布局已设置 maxLines）
        holder.tvCoreReq.setText("核心要求：" + task.getCoreRequirements());
        // 提交率保留两位小数，显示为百分比
        holder.tvSubmissionRate.setText(String.format("提交率：%.2f%%", task.getSubmissionRate()));
        holder.tvViewCount.setText("查看次数：" + task.getViewCount());
        holder.tvDiscussionCount.setText("讨论次数：" + task.getDiscussionCount());
    }

    @Override
    public int getItemCount() {
        return taskList.size();
    }

    /**
     * ViewHolder：缓存任务项控件
     */
    static class TaskViewHolder extends RecyclerView.ViewHolder {
        TextView tvTaskName;
        TextView tvDeadline;
        TextView tvCoreReq;
        TextView tvSubmissionRate;
        TextView tvViewCount;
        TextView tvDiscussionCount;

        public TaskViewHolder(@NonNull View itemView) {
            super(itemView);
            // 绑定布局控件（与 item_task.xml 中 ID 一致）
            tvTaskName = itemView.findViewById(R.id.tv_task_name);
            tvDeadline = itemView.findViewById(R.id.tv_deadline);
            tvCoreReq = itemView.findViewById(R.id.tv_core_req);
            tvSubmissionRate = itemView.findViewById(R.id.tv_submission_rate);
            tvViewCount = itemView.findViewById(R.id.tv_view_count);
            tvDiscussionCount = itemView.findViewById(R.id.tv_discussion_count);
        }
    }
}